package websocket

import (
	"bufio"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"os/exec"
)

func handleWebSocket(c *gin.Context) {
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Printf("Error upgrading to websocket: %v\n", err)
		return
	}
	defer ws.Close()

	executeCommand(ws)
}

func executeCommand(ws *websocket.Conn) {
	cmd := exec.Command("your_command", "arg1", "arg2")

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error getting stdout pipe: %v\n", err)
		return
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error getting stderr pipe: %v\n", err)
		return
	}

	if err := cmd.Start(); err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	stdoutScanner := bufio.NewScanner(stdout)
	go func() {
		for stdoutScanner.Scan() {
			msg := stdoutScanner.Text()
			ws.WriteMessage(websocket.TextMessage, []byte("stdout: "+msg))
		}
	}()

	stderrScanner := bufio.NewScanner(stderr)
	go func() {
		for stderrScanner.Scan() {
			msg := stderrScanner.Text()
			ws.WriteMessage(websocket.TextMessage, []byte("stderr: "+msg))
		}
	}()

	cmd.Wait()
	ws.WriteMessage(websocket.TextMessage, []byte("Command execution finished"))
}
